package com.kaili.basic.controller;


import com.baomidou.mybatisplus.plugins.Page;

import com.kaili.basic.pojo.dto.MdmGroupAddDto;
import com.kaili.basic.pojo.dto.MdmGroupQueryByPageDto;
import com.kaili.basic.pojo.dto.MdmGroupUpdateDto;
import com.kaili.basic.pojo.entity.MdmGroupEntity;
import com.kaili.basic.pojo.vo.MdmGroupQueryAllVo;
import com.kaili.basic.pojo.vo.MdmQueryGroupByIdVo;
import com.kaili.basic.service.IMdmGroupService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.exception.RestException;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.ExcelUtil;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.common.util.ObjectUtils;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "分组管理",description = "分组相关API")
@RestController
public class MdmGroupController {
    public volatile String groupCode;
    @Autowired
    private IMdmGroupService mdmGroupService;

    private static Logger log = LoggerFactory.getLogger(MdmGroupController.class);
    /**
    * @Desc:  分页查询分组管理
    * @author: TBS
    * @Time: 2019/8/9 11:22
    * @param mdmGroupQueryByPageDto
    * @return com.baomidou.mybatisplus.plugins.Page<com.kaili.basic.pojo.vo.MdmGroupQueryAllVo>
    */
    @ApiOperation(value = "分页查询分组管理")
    @GetMapping("/group")
    public Page<MdmGroupQueryAllVo> queryPageList (MdmGroupQueryByPageDto mdmGroupQueryByPageDto){

        return mdmGroupService.queryPageList(new Page<>(mdmGroupQueryByPageDto.getPage(),mdmGroupQueryByPageDto.getPageSize()),mdmGroupQueryByPageDto);
    }
    /**
    * @Desc:  通过ID精确查询分组管理
    * @author: TBS
    * @Time: 2019/8/9 11:22
    * @param id
    * @return com.kaili.basic.pojo.vo.MdmQueryGroupByIdVo
    */
    @ApiOperation(value = "通过ID精确查询分组管理")
    @GetMapping("group/byId/{id}")
    public MdmQueryGroupByIdVo queryGroupById(@PathVariable("id") int id){

        return mdmGroupService.queryGroupById(id);
    }
    /**
    * @Desc:  通过机构ID查询所属机构下的所有分组
    * @author: TBS
    * @Time: 2019/8/9 11:21
    * @param id
    * @return java.util.List<com.kaili.basic.pojo.entity.MdmGroupEntity>
    */
    @ApiOperation(value = "通过机构ID查询所属机构下的所有分组")
    @GetMapping("group/byOrgId/{id}")
    public List<MdmGroupEntity> queryGroupByOrgId(@PathVariable("id") int id) {
        return mdmGroupService.queryGroupByOrgId(id);
    }

    /**
    * @Desc:  新增分组管理
    * @author: TBS
    * @Time: 2019/8/9 11:21
    * @param mdmGroupAddDto
    * @return com.kaili.common.response.RestStatus
    */
    @ApiOperation( value = "新增分组管理")
    @PostMapping("/group/add")
    public RestStatus addGroup(@Validated @RequestBody MdmGroupAddDto mdmGroupAddDto){
        MdmGroupEntity mdmGroupEntity1 = new MdmGroupEntity();
        mdmGroupEntity1.setGroupName(mdmGroupAddDto.getGroupName());
        Integer count = mdmGroupService.queryDprvGroup(mdmGroupEntity1);
        if(count>0) {
            return CommonStatus.RENT_REPETITION;
        }
        String parentIds = mdmGroupService.queryParentGroupId(mdmGroupAddDto.getParentId());
        String parentId[] = parentIds.split(",");
        if(parentId.length>=4) {
            return CommonStatus.ADD_GROUPFAIL;
        }
        mdmGroupAddDto.setCreateBy(LoginDetailUtils.getCurrent().getId());
        mdmGroupAddDto.setCreateTime(new Date());
        MdmGroupEntity mdmGroupEntity =ObjectUtils.toObject(mdmGroupAddDto, MdmGroupEntity.class);
        mdmGroupService.add(mdmGroupEntity);
        return CommonStatus.ADD_OK;
    }

    /***
    * @Desc:
    * @author: TBS
    * @Time: 2019/8/5 10:19
    * @param id
    * @return com.kaili.common.response.RestStatus
    */
    @ApiOperation(value = "删除分组管理")
    @DeleteMapping("/group/{id}")
    public RestStatus deleteGroup(@PathVariable("id") int id){
        mdmGroupService.delete(id);
        return CommonStatus.DELETE_OK;
    }

    /**
    * @Desc:  修改分组管理
    * @author: TBS
    * @Time: 2019/8/9 11:22
    * @param mdmGroupUpdateDto
    * @return com.kaili.common.response.RestStatus
    */
    @ApiOperation(value = "修改分组管理")
    @PutMapping("/group")
    public RestStatus updateGroup(@RequestBody MdmGroupUpdateDto mdmGroupUpdateDto){
        mdmGroupUpdateDto.setModifyBy(LoginDetailUtils.getCurrent().getId());
        mdmGroupUpdateDto.setModifyTime(new Date());
        MdmGroupEntity mdmGroupEntity = ObjectUtils.toObject(mdmGroupUpdateDto, MdmGroupEntity.class);
        mdmGroupService.update(mdmGroupEntity);
        return CommonStatus.UPDATE_OK;
    }



    /**
    * @Desc:  分组管理导出
    * @author: TBS
    * @Time: 2019/8/9 11:22
    * @param response
    * @param mdmGroupQueryByPageDto
    * @return void
    */
    @ApiOperation(value = "分组管理导出")
    @GetMapping("/group/export")
    public void export(HttpServletResponse response,@ModelAttribute MdmGroupQueryByPageDto mdmGroupQueryByPageDto) throws RestException{
        List<MdmGroupQueryAllVo> list = mdmGroupService.queryGroupExport(mdmGroupQueryByPageDto);
        ExcelUtil.exportExcel(list,"分组管理","sheet1", MdmGroupQueryAllVo.class, UUID.randomUUID().toString()+".xls",response);
    }

    /**
    * @Desc:  分组管理导入
    * @author: TBS
    * @Time: 2019/8/9 11:22
    * @param file
    * @return void
    */
    @ApiOperation(value = "分组管理导入")
    @PostMapping("/group/import")
    public void export(MultipartFile file) throws RestException{
        List<MdmGroupQueryAllVo> list = ExcelUtil.importExcel(file,1,1, MdmGroupQueryAllVo.class);
        MdmGroupEntity mdmGroupEntity;
        for (MdmGroupQueryAllVo mdmGroupQueryAllVo :list){
            mdmGroupQueryAllVo.setCreateBy(LoginDetailUtils.getCurrent().getId());
            mdmGroupQueryAllVo.setCreateTime(new Date());
            mdmGroupEntity = ObjectUtils.toObject(mdmGroupQueryAllVo, MdmGroupEntity.class);
            mdmGroupService.add(mdmGroupEntity);
        }
    }

    /**
    * @Desc:  新增分组时获取分组编号
    * @author: TBS
    * @Time: 2019/8/9 11:23
    *
    * @return java.lang.String
    */
    @ApiOperation(value = "新增分组时获取分组编号")
    @GetMapping("group/code")
    public String getGroupCode(){

        if(!StringUtils.isEmpty(groupCode)) {
            groupCode = addValue(groupCode);
            return groupCode;
        }String code = mdmGroupService.getCode();
        String groupCode = addValue(code);
        return groupCode;
    }

    /**
    * @Desc: 新增分组时获取分组编号 调用addValue方法
    * @author: TBS
    * @Time: 2019/8/9 11:23
    * @param str
    * @return java.lang.String
    */
    public static String addValue(String str){
        Integer str1 = Integer.parseInt(str);
        String str2 = str1.toString();
        int index = str.length()-str2.length()-1;

        int temp =0;
        //以0开头的
        if (str.startsWith("0")&&index!=-1){
            temp=index+1;
        }
        Integer integer = null;
        try {
            integer = Integer.valueOf(str);
        } catch (NumberFormatException e) {
            log.info("输入的字符串不是纯数字字符串...");
        }
        integer++;
        String newNum = integer.toString();

        if (newNum.length()>str.length()-temp){
            temp--;
        }
        StringBuffer sb = new StringBuffer();
        if (temp!=0){
            for (int i =0 ;i<temp ;i++){
                sb.append("0");
            }
        }
        sb.append(newNum);
        return sb.toString();
    }




}
